package org.interfaceadaptation.parameter.expression.converter.impl;

import java.lang.reflect.Method;

import org.interfaceadaptation.InterfaceAdaptationError;
import org.interfaceadaptation.parameter.expression.converter.Converter;
import org.interfaceadaptation.util.ReflectionUtils;

public class ValueOfConverter implements Converter {

    private Class<?> from;

    private Class<?> to;

    private Method staticValueOf;

    public ValueOfConverter(Class<?> from, Class<?> to) {
        this.from = from;
        this.to = to;
        this.staticValueOf = getStaticValueOf(from, to);
    }

    public Class<?> getFromClass() {
        return from;
    }

    public Class<?> getToClass() {
        return to;
    }

    
	public Object from(Object value) {
		if (!from.isAssignableFrom(value.getClass())) {
			throw new InterfaceAdaptationError("value of class " + value.getClass()+" is not assignable to " + from.getName());
		}
        return  ReflectionUtils.invoke(staticValueOf, null, value);
    }

    private Method getStaticValueOf(Class<?> from, Class<?> to) {
        if (!ReflectionUtils.hasStaticValueOf(to, from)) {
            throw new InterfaceAdaptationError("Could not find static valueOf(" + from.getName() + ") for class "
                    + to.getName());
        }
        return ReflectionUtils.getStaticValueOf(to, from);
        
    }
    
    @Override
    public String toString() {
    	return "from "+ from.getSimpleName() + " to " + to.getSimpleName();
    }

}